package leetcode;


public class l0023_合并K个升序链表_5_分治策略_推荐采用这种 {

    public ListNode mergeKLists(ListNode[] lists) {
        //前置校验
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }
        int step = 1;
        while (step < lists.length) {
            //跳出循环的，是因为此次的步长已经合并完了
            //i=i                           i+step
            //i=i+step+step=i+2*step        i+step
            for (int i = 0; i + step < lists.length; i = i + 2 * step) {
                //两两合并
                lists[i] = mergeTwoLists(lists[i], lists[i + step]);
            }
            step = step << 1;
        }
        return lists[0];
    }

    private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //前置校验
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            } else {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }
        if (list1 != null) {
            cur.next = list1;
        }
        if (list2 != null) {
            cur.next = list2;
        }
        return dummyHead.next;
    }

}
